package com.sumainfor.common.wechat;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.Map.Entry;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class WxXmlUtil {
	static Logger logger = LoggerFactory.getLogger(WxXmlUtil.class);
	
	  /**
     * 解析xml,返回第一级元素键值对。如果第一级元素有子节点，则此节点的值是子节点的xml数据。
     * @param strxml
     * @return
     * @throws IOException
     */
    public static Map<String,String> doXMLParse(String strxml) throws Exception {
        strxml = strxml.replaceFirst("encoding=\".*\"", "encoding=\"UTF-8\"");

        if(null == strxml || "".equals(strxml)) {
            return null;
        }
        Map<String,String> m = new HashMap<String, String>();
        InputStream in = new ByteArrayInputStream(strxml.getBytes("UTF-8"));
        SAXBuilder builder = new SAXBuilder();
        Document doc = builder.build(in);
        Element root = doc.getRootElement();
        List list = root.getChildren();
        Iterator it = list.iterator();
        while(it.hasNext()) {
            Element e = (Element) it.next();
            String k = e.getName();
            String v = "";
            List children = e.getChildren();
            if(children.isEmpty()) {
                v = e.getTextNormalize();
            } else {
                v = getChildrenText(children);
            }
            m.put(k, v);
        }
        
        //关闭流
        in.close();
        
        return m;
    }
    
    /**
     * 获取子结点的xml
     * @param children
     * @return String
     */
    public static String getChildrenText(List children) {
        StringBuffer sb = new StringBuffer();
        if(!children.isEmpty()) {
            Iterator it = children.iterator();
            while(it.hasNext()) {
                Element e = (Element) it.next();
                String name = e.getName();
                String value = e.getTextNormalize();
                List list = e.getChildren();
                sb.append("<" + name + ">");
                if(!list.isEmpty()) {
                    sb.append(getChildrenText(list));
                }
                sb.append(value);
                sb.append("</" + name + ">");
            }
        }
        return sb.toString();
    }
    
    /**
     * 将信息加密返回
     * @param result
     * @return
     * @throws Exception
     */
    public static TreeMap<String,Object> toMap(String result,String MchId) throws Exception{
    	//处理返回参数xml格式的字符串转化为map
    	Map<String,String> map = doXMLParse(result);
    	HashMap<String,Object> hm = new HashMap<String, Object>();
    	 Iterator<Entry<String, String>> it = map.entrySet().iterator();
         while(it.hasNext()){
        	 Entry<String,String> entry = it.next();
        	 if("prepay_id".equals(entry.getKey()))
            	 hm.put("prepay_id", entry.getValue());
        	 if("nonce_str".equals(entry.getKey()))
            	 hm.put("nonce_str", entry.getValue());
        	 if("result_code".equals(entry.getKey()))
            	 hm.put("result_code", entry.getValue());
        	 if("return_code".equals(entry.getKey()))
            	 hm.put("return_code", entry.getValue());
//        	 if("sign".equals(entry.getKey()))
//            	 hm.put("sign", entry.getValue());
         }
         hm.put("timestamp", WxEncodeUtil.getTimeStamp());
         hm.put("appid", WeChatConfig.APP_ID);
         hm.put("mch_id",MchId);
    	return WxEncodeUtil.signMdAgain(hm);
    }
    
    /**
     * 将请求参数转换为xml格式的string字符串，微信服务器接收的是xml格式的字符串
     * @param parameters
     * @return
     */
    public static String getRequestXml(SortedMap<Object, Object> parameters) {
        StringBuffer sb = new StringBuffer();
        sb.append("<xml>");
        Set<Entry<Object, Object>> es = parameters.entrySet();
        Iterator<Entry<Object, Object>> it = es.iterator();
        while (it.hasNext()) {
            Entry<Object, Object> entry = (Entry<Object, Object>) it.next();
            String k = (String) entry.getKey();
            String v = (String) entry.getValue();
            
            if ("attach".equalsIgnoreCase(k) || "body".equalsIgnoreCase(k) || "sign".equalsIgnoreCase(k)) {
                sb.append("<" + k + ">" + "<![CDATA[" + v + "]]></" + k + ">");
            } else {
                sb.append("<" + k + ">" + v + "</" + k + ">");
            }
        }
        sb.append("</xml>");
        return sb.toString();
    }
    
    /** 
     * 签名校验
     * 是否签名正确,规则是:按参数名称a-z排序,遇到空值的参数不参加签名 。 
     * @return boolean 
     */  
    public static boolean isTenpaySign(String characterEncoding, SortedMap<Object, Object> packageParams, String API_KEY) {  
        StringBuffer sb = new StringBuffer();  
        Set es = packageParams.entrySet();  
        Iterator it = es.iterator();  
        while(it.hasNext()) {  
            Entry entry = (Entry)it.next();
            String k = (String)entry.getKey();  
            String v = (String)entry.getValue();  
            if(!"sign".equals(k) && null != v && !"".equals(v)) {  
                sb.append(k + "=" + v + "&");  
            }  
        }  
        sb.append("key=" + API_KEY);  
        String mysign = WxEncodeUtil.MD5Encode(sb.toString(), characterEncoding).toLowerCase();  
        String tenpaySign = ((String)packageParams.get("sign")).toLowerCase();  
        return tenpaySign.equals(mysign);  
    }  

	
	
}
